package com.rd.utils;

import cn.hutool.core.lang.UUID;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private String keyName;

    private StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX = "myLock:";

    private static final String ID_PREFIX = UUID.randomUUID().toString(true);

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static {
        // 创建DefaultRedisScript对象并从类路径中加载lua脚本
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String keyName, StringRedisTemplate stringRedisTemplate) {
        this.keyName = keyName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程id
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean res = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + keyName,threadId, timeoutSec, TimeUnit.SECONDS);
        // Boolean 返回 boolean
        // 直接返回可能会有拆箱问题，空指针异常
        return Boolean.TRUE.equals(res);
    }

    @Override
    public void unlock() {
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        val id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + keyName);
        // 防止锁误删问题
        if (threadId.equals(id)){
            stringRedisTemplate.delete(KEY_PREFIX + keyName);
        }
    }

    public void unlockByLuaScript() {
        String threadId = ID_PREFIX + Thread.currentThread().getId();

        // 执行 lua脚本
        //execute(script,keys,argv); 对应lua脚本中的 KEYS 和 ARGV
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Arrays.asList(KEY_PREFIX + keyName),threadId);

    }
}
